package so.shanku.essential.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.*;
import aym.util.getservicesdata.GetServicesDataQueue;
import aym.util.getservicesdata.GetServicesDataUtil;
import aym.util.json.JsonMap;
import aym.util.json.JsonMapOrListJsonMap2JsonUtil;
import aym.util.json.JsonParseHelper;
import net.tsz.afinal.annotation.view.ViewInject;
import so.shanku.essential.R;
import so.shanku.essential.activity.base.BaseUIActivity;
import so.shanku.essential.adapter.UserOrderAdapter;
import so.shanku.essential.getdata.GetDataConfing;
import so.shanku.essential.getdata.GetDataQueue;
import so.shanku.essential.getdata.JsonKeys;
import so.shanku.essential.getdata.ShowGetDataError;
import so.shanku.essential.utils.Constant;
import so.shanku.essential.utils.ExtraKeys;
import so.shanku.essential.utils.LogUtil;
import so.shanku.essential.utils.Utils;
import so.shanku.essential.view.BadgeView;
import striveen.util.used.view.view.XListView;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2015/9/9.
 */
public class UserOrderActivity extends BaseUIActivity implements UserOrderAdapter.UserOrderItemCompountClickListener {
    /**
     * 搜索框的隐藏与显示
     */
    @ViewInject(id = R.id.linearlayout_search)
    private LinearLayout linearlayout_search;
    /**
     * 搜索商品
     */
    @ViewInject(id = R.id.search_ed)
    private EditText search_ed;
    /**
     * 搜索取消
     */
    @ViewInject(id = R.id.tv_search_cancel, click = "search_cancel_click")
    private TextView tv_search_cancel;

    /**
     * 订单类别控件
     */
    @ViewInject(id = R.id.order_classfy_layout)
    private LinearLayout order_classfy_layout;

    /**
     * 全部订单
     */
    @ViewInject(id = R.id.all_order_layout, click = "all_order_layout_click")
    private LinearLayout all_order_layout;
    @ViewInject(id = R.id.all_order_tv)
    private TextView all_order_tv;

    /**
     * 待付款订单
     */
    @ViewInject(id = R.id.unpaid_order_layout, click = "unpaid_order_layout_click")
    private LinearLayout unpaid_order_layout;
    @ViewInject(id = R.id.unpaid_order_tv)
    private TextView unpaid_order_tv;
    private BadgeView unpaid_order_badgeView;

    /**
     * 待发货订单
     */
    @ViewInject(id = R.id.unshipped_order_layout, click = "unshipped_order_layout_click")
    private LinearLayout unshipped_order_layout;
    @ViewInject(id = R.id.unshipped_order_tv)
    private TextView unshipped_order_tv;
    private BadgeView unshipped_order_badgeView;

    /**
     * 待收货订单
     */
    @ViewInject(id = R.id.no_receiver_order_layout, click = "no_receiver_order_layout_click")
    private LinearLayout no_receiver_order_layout;
    @ViewInject(id = R.id.no_receiver_order_tv)
    private TextView no_receiver_order_tv;
    private BadgeView no_receiver_order_badgeView;


    @ViewInject(id = R.id.xlistview_order)
    private XListView xlistview_order;
    private UserOrderAdapter userOrderAdapter;
    /**
     * 无相关数据
     */
    @ViewInject(id = R.id.nodata_layout,click = "nodata_layout_click")
    private LinearLayout nodata_layout;

    /**
     * 待付款
     */
    private String  unpaidCount ="";
    /**
     * 待发货
     */
    private String unShippedCount ="";
    /**
     * 待收货
     */
    private String not_receiver_Count ="";


    /**
     * 当前选中项
     */
    private int currentSelected=-1;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user_order);
        setCenter_title(R.string.user_order);
        setBtn_menuText(R.string.aftermarket, new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                order_search_click();
            }
        });
        search_ed.setHint(R.string.search_all_order);
        xlistview_order.setXListViewListener(xListLoadMore);
        xlistview_order.setBoolInterceptTouchEvent(false);
        setCurrentSelectItem(0);
        unpaid_order_badgeView=new BadgeView(this,unpaid_order_tv);
        unpaid_order_badgeView.setTextSize(10);
        unpaid_order_badgeView.setText(unpaidCount);
        unpaid_order_badgeView.setBadgeMargin(getResources().getDimensionPixelSize(R.dimen.comon_half_margin));

        unshipped_order_badgeView=new BadgeView(this,unshipped_order_tv);
        unshipped_order_badgeView.setTextSize(10);
        unshipped_order_badgeView.setText(unShippedCount);
        unshipped_order_badgeView.setBadgeMargin(getResources().getDimensionPixelSize(R.dimen.comon_half_margin));

        no_receiver_order_badgeView=new BadgeView(this,no_receiver_order_tv);
        no_receiver_order_badgeView.setTextSize(10);
        no_receiver_order_badgeView.setText( not_receiver_Count);
        no_receiver_order_badgeView.setBadgeMargin(getResources().getDimensionPixelSize(R.dimen.comon_half_margin));
    }

    /**
     *
     * @param view
     */
    public void nodata_layout_click(View view){
        //getData_UserBrand(true);
    }
    /**
     * 所有订单
     * @param view
     */
    public void all_order_layout_click(View view){
        setCurrentSelectItem(0);
    }

    public void unpaid_order_layout_click(View view){
        setCurrentSelectItem(1);
    }

    public void unshipped_order_layout_click(View view){
        setCurrentSelectItem(2);
    }

    public void no_receiver_order_layout_click(View view){
        setCurrentSelectItem(3);
    }

    /**
     * 设置当前选项 并重新请求数据
     * @param selected
     */
    private void setCurrentSelectItem(int selected) {
        if(currentSelected!=selected){
            if(currentSelected!=-1) {
                setSelected(false);
            }
            currentSelected=selected;
            setSelected(true);
            getData_UserBrand(true);
        }
    }

    /**
     * 更改类别显示状态
     * @param b
     */
    private void setSelected(boolean b) {
        order_classfy_layout.getChildAt(currentSelected).setSelected(b);
    }

    XListView.IXListViewListener xListLoadMore = new XListView.IXListViewListener() {
        @Override
        public void onRefresh() {
            getData_UserBrand(true);
        }

        @Override
        public void onLoadMore() {
            getData_UserBrand(false);
        }
    };

    /**
     * 售后
     */
    public void order_search_click() {
        jumpTo(ProductAfterMarketActivity.class);
    }


    /**
     * 我的订单接口
     */
    private int pageSize = 10;
    private int page = 0;
    private List<JsonMap<String, Object>> data_OrderList;

    private void getData_UserBrand(boolean chearAllData) {

        if (chearAllData) {
            loadingToast.show();
            data_OrderList = null;
            if (userOrderAdapter != null) {
                userOrderAdapter.notifyDataSetChanged();
            }
            page = 0;
            xlistview_order.setPullRefreshEnable(true);
            xlistview_order.setPullLoadEnable(true);
        }
        Map<String, Object> params = new HashMap<String, Object>();
        params.put(GetDataQueue.Params_key,GetDataConfing.Key_Str) ;
        params.put("userName", Utils.getUserId(this));
        if(currentSelected==3) {
            params.put("OrderStatusId", currentSelected+1);
        } else {
            params.put("OrderStatusId", currentSelected);

        }
        params.put("currentPage", page + 1);
        params.put("pageSize", pageSize);
        GetDataQueue queue = new GetDataQueue();
        queue.setCallBack(callBack);
        queue.setActionName(GetDataConfing.Action_GetOrderByOrderStatusId);
        queue.setWhat(GetDataConfing.What_getOrderByOrderStatusId);
        queue.setParamsNoJson(params);
        getDataUtil.getData(queue);
    }


    private void setAdatper_singleSortlist(final List<JsonMap<String, Object>> data) {

        if (data.size() == 0 || data.size() % pageSize != 0) {
            xlistview_order.setPullLoadEnable(false);
        }
        if (page == 0) {
            this.data_OrderList = data;
            userOrderAdapter = new UserOrderAdapter(this, data_OrderList);
            userOrderAdapter.setTag(0);
            xlistview_order.setAdapter(userOrderAdapter);
            userOrderAdapter.setUserOrderItemCompountClickListener(this);
        } else {
            this.data_OrderList.addAll(data);
            userOrderAdapter.notifyDataSetChanged();
        }
        page++;
    }

    /**
     * 获取服务器数据的返回信息
     */
    private GetServicesDataUtil.IGetServicesDataCallBack callBack = new GetServicesDataUtil.IGetServicesDataCallBack() {
        @Override
        public void onLoaded(GetServicesDataQueue entity) {
            if (entity.isOk()) {
                if (ShowGetDataError.isCodeSuccess(UserOrderActivity.this,
                        entity.getInfo())) {
                    if (entity.what == GetDataConfing.What_getOrderByOrderStatusId) {
                        JsonMap jsonMap1=JsonParseHelper.getJsonMap_JsonMap(entity.getInfo(), JsonKeys.Key_Info);
                        List<JsonMap<String, Object>> data = jsonMap1.getList_JsonMap("OrderList");
                        setOrderStatueNum(jsonMap1);
                        setAdatper_singleSortlist(data);
                    } else if (entity.what == GetDataConfing.What_GetHistoryUserOrderByPageNum) {
                        JsonMap jsonMap1=JsonParseHelper.getJsonMap_JsonMap(entity.getInfo(), JsonKeys.Key_Info);
                        List<JsonMap<String, Object>> data = jsonMap1.getList_JsonMap("OrderList");
                        setOrderStatueNum(jsonMap1);
                        setAdatperDataByPageNum(data);
                    } else if (entity.what == GetDataConfing.what_UpdateOrdersbyOrderNum) {
                        toast.showToast(R.string.shopping_order_option_success);
                        getHistoryOders();
                    } else if (entity.what == GetDataConfing.What_ReturnFundByOrderNum) {
                        getHistoryOders();
                        toast.showToast(R.string.shopping_order_option_success);
                    } else if (entity.what == GetDataConfing.What_ConfirmOrdersByOrderNum) {
                        getHistoryOders();
                        toast.showToast(R.string.shopping_order_option_success);
                    }
                }
            } else {
                ShowGetDataError.showNetError(UserOrderActivity.this);
            }
            loadingToast.dismiss();
            invalidateListData();
            xlistview_order.stopLoadMore();
            xlistview_order.stopRefresh();
        }
    };

    /**
     * 设置订单数量提示
     * @param data
     */
    private void setOrderStatueNum(JsonMap data) {
        unpaidCount=data.getStringNoNull("ForThepaymentCount");
        unShippedCount=data.getStringNoNull("ToSendTheGoodsCount");
        not_receiver_Count=data.getStringNoNull("ForTheGoodsCount");
        if(TextUtils.isEmpty(unpaidCount)||unpaidCount.equals("0")){
             unpaid_order_badgeView.hide();
        } else {
            unpaid_order_badgeView.setText(unpaidCount);
            unpaid_order_badgeView.show(true);
        }

        if(TextUtils.isEmpty(unShippedCount)||unShippedCount.equals("0")){
            unshipped_order_badgeView.hide();
        } else {
            unshipped_order_badgeView.setText(unShippedCount);
            unshipped_order_badgeView.show(true);
        }

        if(TextUtils.isEmpty(not_receiver_Count)||not_receiver_Count.equals("0")){
            no_receiver_order_badgeView.hide();
        } else {
            no_receiver_order_badgeView.setText(not_receiver_Count);
            no_receiver_order_badgeView.show(true);
        }
    }

    /**
     * 设置数据 并华东到上个位置
     *
     * @param data
     */
    private void setAdatperDataByPageNum(final List<JsonMap<String, Object>> data) {

        if (data.size() == 0 || data.size() % pageSize != 0) {
            xlistview_order.setPullLoadEnable(false);
        }
        this.data_OrderList = data;
        userOrderAdapter = new UserOrderAdapter(this, data_OrderList);
        userOrderAdapter.setTag(0);
        xlistview_order.setAdapter(userOrderAdapter);
        userOrderAdapter.setUserOrderItemCompountClickListener(this);
//        if(firstItemPosition<data_OrderList.size()) {
//            xlistview_order.setSelection(firstItemPosition);
//        }
    }

    /**
     * 记录当前显示的第一个item的位置
     */
    int firstItemPosition = 0;

    /**
     * 获取历史以查询的订单
     */
    private void getHistoryOders() {
        getData_UserBrand(true);
//        firstItemPosition = xlistview_order.getFirstVisiblePosition();
//        page = 0;
//        loadingToast.show();
//        data_OrderList = null;
//        if (userOrderAdapter != null) {
//            userOrderAdapter.notifyDataSetChanged();
//        }
//        xlistview_order.setPullRefreshEnable(true);
//        xlistview_order.setPullLoadEnable(true);
//        Map<String, Object> params = new HashMap<String, Object>();
//        params.put(GetDataQueue.Params_key, "orderCreateTime");
//        params.put("userName", Utils.getUserAccount(this));
//        params.put("currentPage", page + 1);
//        params.put("pageSize", pageSize);
//        GetDataQueue queue = new GetDataQueue();
//        queue.setCallBack(callBack);
//        queue.setActionName(GetDataConfing.Action_GetHistoryUserOrderByPageNum);
//        queue.setWhat(GetDataConfing.What_GetHistoryUserOrderByPageNum);
//        queue.setParamsNoJson(params);
//        getDataUtil.getData(queue);
    }

    private void invalidateListData() {
        if (data_OrderList == null || data_OrderList.size() < 1) {
            xlistview_order.setVisibility(View.GONE);
            nodata_layout.setVisibility(View.VISIBLE);
        } else {
            xlistview_order.setVisibility(View.VISIBLE);
            nodata_layout.setVisibility(View.GONE);
        }
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        if(isNeedRefreshData) {
            getHistoryOders();
            isNeedRefreshData=false;
        }
    }

    JsonMap jsonMap;
    private boolean isNeedRefreshData=false;
    @Override
    public void userOrderItemCompountClick(int position, Constant.UserOrderItemType userOrderItemType,int childPosition) {
        jsonMap = data_OrderList.get(position);
        String orderNum = jsonMap.getStringNoNull("OrderNum");
        String orderId=jsonMap.getStringNoNull("Id");
        isNeedRefreshData=true;
        if(userOrderItemType== Constant.UserOrderItemType.SEE_PRODUCT){
//            ArrayList<JsonMap<String,Object>> dataList = (ArrayList<JsonMap<String, Object>>) jsonMap.getList_JsonMap("OrderdetailList");
//            String productId=dataList.get(childPosition).getStringNoNull("ProductId");
//            seeProductDetail(productId);
            seeOrderDetail(orderNum);
        }else if (userOrderItemType == Constant.UserOrderItemType.SEELogistics) {  //物流
             isNeedRefreshData=false;
            seeLogistics(orderNum);
        } else if (userOrderItemType == Constant.UserOrderItemType.SEE_ORDER_DETAIL) { //订单详情
            seeOrderDetail(orderNum);
        } else if (userOrderItemType == Constant.UserOrderItemType.SEE_BRAND) {
            isNeedRefreshData=false;
            seeShopThemeDetail(jsonMap.getStringNoNull("VendorId"));
        } else if (userOrderItemType == Constant.UserOrderItemType.CANCEL_ORDER) {  //cancel order
            getData_Cancel_Order(orderId, callBack);
        } else if (userOrderItemType == Constant.UserOrderItemType.ORDER_CONFIRM) { //confirm receive
            goodsReceiveConfirm(orderNum, callBack);
        } else if (userOrderItemType == Constant.UserOrderItemType.FUND_RETURN) {  //apply return fund
            getFundReturn(orderId, callBack);
        } else if (userOrderItemType == Constant.UserOrderItemType.GOODS_RETURN) {  //申请退货
            getGoodsReturn(orderNum, callBack);

        } else if (userOrderItemType == Constant.UserOrderItemType.GOTO_PAY) {   //支付
            LogUtil.d(TAG,"userOrderItemCompountClick SEE_ORDER_DETAIL");
            Intent intent = new Intent(this, ShoppingZhifuPeisongWayActivity.class);
            intent.putExtra(ExtraKeys.Key_Msg1, 1);
            intent.putExtra(ExtraKeys.Key_Msg2,orderNum);
            startActivityForResult(intent, request_payType);
        } else if (userOrderItemType == Constant.UserOrderItemType.DO_GOODS_RETURN) { //进行退货
            doGoodsReturn(orderNum,jsonMap.getStringNoNull("VendorId"));
        }else if (userOrderItemType == Constant.UserOrderItemType.REFUND_DETAIL) {
            isNeedRefreshData=false;
            scanRefundDetail(orderNum);
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            if (requestCode == request_pay) {
            } else if (requestCode == request_payType) {
                LogUtil.d(TAG,"onActivityResult:"+request_payType);
                String payTypeId = data.getStringExtra(ExtraKeys.Key_Msg2);
                startPay(payTypeId);
            }
        }
    }

    /**
     * 请求支付
     */
    int request_pay = 10;
    int request_payType = 20;

    public void startPay(String payTypeId) {
        LogUtil.d(TAG,"startPay");
        toast.showToast(R.string.start_pay);
        JsonMapOrListJsonMap2JsonUtil<String, Object> util = new JsonMapOrListJsonMap2JsonUtil<String, Object>();
        JsonMap<String, Object> orderdata = new JsonMap<String, Object>();
        orderdata.put("OrderNum", jsonMap.getStringNoNull("OrderNum"));
        orderdata.put("productName", "商品名称");
        orderdata.put("ActualPayPrice", jsonMap.getStringNoNull("RealTotal"));
        orderdata.put("selectpayid", payTypeId);
        Intent intent = new Intent(this, CommitOrderActivity.class);
        intent.putExtra(ExtraKeys.Key_Msg1, 2);
        intent.putExtra(ExtraKeys.Key_Msg2, util.map2Json(orderdata));
        startActivityForResult(intent, request_pay);
    }

}
